<template>
  <!-- 搜索条件 -->
  <el-card class="top">
    <el-form class="search-form">
      <!-- 姓名 -->
      <el-form-item label="姓名：" prop="name">
        <el-input
            v-model="searchDataForm.name"
            clearable
            :prefix-icon="User"
            placeholder="请你输入搜索姓名"
        />
      </el-form-item>
      <!-- 学号 -->
      <el-form-item label="学号：" prop="studentNumber">
        <el-input
            v-model="searchDataForm.studentNumber"
            clearable
            :prefix-icon="Postcard"
            placeholder="请你输入搜索学号"
        />
      </el-form-item>
      <!-- 手机号 -->
      <el-form-item label="手机号：" prop="phone">
        <el-input
            v-model="searchDataForm.phone"
            clearable
            :prefix-icon="Iphone"
            placeholder="请你输入搜索手机号"
        />
      </el-form-item>
      <!-- 身份证号 -->
      <el-form-item label="身份证号：" prop="idCard">
        <el-input
            v-model="searchDataForm.idCard"
            clearable
            :prefix-icon="CreditCard"
            placeholder="请你输入搜索身份证号"
        />
      </el-form-item>
      <!-- 按钮 -->
      <el-form-item>
        <el-button type="primary" @click="searchForm">
          搜索
        </el-button>
        <el-button @click="resetForm">
          重置
        </el-button>
      </el-form-item>
    </el-form>
  </el-card>

  <!-- 展示数据 -->
  <el-card class="bottom">
    <!-- 按钮 -->
    <el-button type="primary" @click="addUser">添加</el-button>
    <el-popconfirm title="你确定要批量删除吗？" width="260px"
                   @confirm="deleteSelectUser"
    >
      <template #reference>
        <el-button type="danger" size="default"
                   :disabled="!selectIdArr.length"
        >
          批量删除
        </el-button>
      </template>
    </el-popconfirm>
    <!-- 表格展示用户信息 -->
    <el-table style="width: 100%" height="50vh"
              class="bottom-table"
              :header-cell-style="{'text-align':'center'}"
              :cell-style="{'text-align':'center'}"
              :data="records"
              border
              @selection-change="selectChange"
    >
      <!-- 多选框 -->
      <el-table-column fixed="left" type="selection" width="50"/>
      <!-- 序号 -->
      <el-table-column fixed="left" type="index" label="#" width="50"/>
      <!-- 姓名 -->
      <el-table-column sortable
                       prop="name"
                       label="姓名"
                       width="100"
                       show-overflow-tooltip
      />
      <!-- 性别 -->
      <el-table-column sortable
                       prop="sexText"
                       label="性别"
                       width="80"
                       show-overflow-tooltip
      />
      <!-- 年龄 -->
      <el-table-column sortable
                       prop="age"
                       label="年龄"
                       width="80"
                       show-overflow-tooltip
      />
      <!-- 学号 -->
      <el-table-column sortable
                       prop="studentNumber"
                       label="学号"
                       width="120"
                       show-overflow-tooltip
      />
      <!-- 身份证号 -->
      <el-table-column sortable
                       prop="idCard"
                       label="身份证号"
                       width="180"
                       show-overflow-tooltip
      />
      <!-- 手机号 -->
      <el-table-column sortable
                       prop="phone"
                       label="手机号"
                       width="120"
                       show-overflow-tooltip
      />
      <!-- 学院 -->
      <el-table-column sortable
                       prop="college"
                       label="学院"
                       width="180"
                       show-overflow-tooltip
      />
      <!-- 专业 -->
      <el-table-column sortable
                       prop="major"
                       label="专业"
                       width="180"
                       show-overflow-tooltip
      />
      <!-- 班级 -->
      <el-table-column sortable
                       prop="grade"
                       label="班级"
                       width="80"
                       show-overflow-tooltip
      />
      <!-- 入学时间 -->
      <el-table-column sortable
                       prop="enterTime"
                       label="入学时间"
                       width="180"
                       show-overflow-tooltip
      />
      <!-- 出生日期 -->
      <el-table-column sortable
                       prop="birthday"
                       label="出生日期"
                       width="180"
                       show-overflow-tooltip
      />
      <!-- 邮箱 -->
      <el-table-column sortable
                       prop="email"
                       label="邮箱"
                       show-overflow-tooltip
                       width="180"
      />
      <!-- 地址 -->
      <el-table-column sortable
                       prop="address"
                       label="地址"
                       show-overflow-tooltip
                       width="180"
      />
      <!-- 操作 -->
      <el-table-column fixed="right" label="操作" width="180">
        <template #default="props">
          <el-button type="primary"
                     icon="Edit"
                     size="small"
                     @click="updateUser(props.row)"
          >
            编辑
          </el-button>
          <el-popconfirm :title="`你确定要删除${props.row.name}?`" width="260px"
                         @confirm="deleteUser(props.row.id)"
          >
            <template #reference>
              <el-button type="danger"
                         size="small"
                         icon="Delete"
              >
                删除
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination v-model:current-page="pageNum"
                   v-model:page-size="pageSize"
                   :page-sizes="[5, 10, 15, 20]"
                   :background="true"
                   layout="prev, pager, next, jumper,->,sizes,total"
                   :total="totalRow"
                   @current-change="searchForm"
                   @size-change="searchForm"
    />
  </el-card>

  <!-- 抽屉结构:完成添加新的用户账号|更新已有的账号信息 -->
  <el-dialog v-model="drawer">
    <!-- 头部标题:将来文字内容应该动态的 -->
    <template #header>
      <h4>{{ userParams.id ? '更新用户' : '添加用户' }}</h4>
    </template>
    <!-- 身体部分 -->
    <template #default>
      <el-form :model="userParams"
               :rules="rules"
               ref="ruleFormRef"
               :inline="true"
               label-position="top"
               class="dialog-add-or-update-form"
      >
        <!-- 用户账号 -->
        <el-form-item label="用户账号" prop="username" v-if="!userParams.id">
          <el-input placeholder="请您输入用户账号"
                    v-model="userParams.username"
                    maxlength="20"
                    show-word-limit
                    clearable
          />
        </el-form-item>
        <!-- 用户密码 -->
        <el-form-item label="用户密码" prop="password" v-if="!userParams.id">
          <el-input placeholder="请您输入用户密码"
                    v-model="userParams.password"
                    maxlength="20"
                    show-word-limit
                    clearable
          />
        </el-form-item>

        <el-form-item label="用户姓名：" prop="name">
          <el-input
              v-model="userParams.name"
              placeholder="请输入用户姓名"
              clearable
              show-word-limit
              maxlength="50"
          />
        </el-form-item>

        <el-form-item label="用户性别：" prop="sex">
          <el-radio-group v-model="userParams.sex">
            <el-radio value="1">男</el-radio>
            <el-radio value="2">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="用户学号：" prop="studentNumber">
          <el-input
              v-model="userParams.studentNumber"
              placeholder="请输入用户学号"
              clearable
              show-word-limit
              maxlength="20"
          />
        </el-form-item>

        <el-form-item label="用户年龄：" prop="age">
          <el-input-number v-model="userParams.age"
                           style="width: 62%"
                           controls-position="right"
                           placeholder="请输入用户年龄"
                           show-word-limit
                           :max="999"
          >
            <template #decrease-icon>
              <el-icon>
                <Minus/>
              </el-icon>
            </template>
            <template #increase-icon>
              <el-icon>
                <Plus/>
              </el-icon>
            </template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="用户电话：" prop="phone">
          <el-input
              v-model="userParams.phone"
              placeholder="请输入用户电话"
              clearable
              show-word-limit
              maxlength="20"
          />
        </el-form-item>

        <el-form-item label="用户邮箱：" prop="email">
          <el-input
              v-model="userParams.email"
              placeholder="请输入用户邮箱"
              clearable
              show-word-limit
              maxlength="100"
          />
        </el-form-item>

        <el-form-item label="用户学院：" prop="college">
          <el-input
              v-model="userParams.college"
              placeholder="请输入用户学院"
              clearable
              show-word-limit
              maxlength="100"
          />
        </el-form-item>

        <el-form-item label="用户专业：" prop="major">
          <el-input
              v-model="userParams.major"
              placeholder="请输入用户专业"
              clearable
              show-word-limit
              maxlength="100"
          />
        </el-form-item>

        <el-form-item label="用户班级：" prop="grade">
          <el-input
              v-model="userParams.grade"
              placeholder="请输入用户班级"
              clearable
              show-word-limit
              maxlength="100"
          />
        </el-form-item>

        <el-form-item label="身份证号：" prop="idCard">
          <el-input
              v-model="userParams.idCard"
              placeholder="请输入身份证号"
              clearable
              show-word-limit
              maxlength="20"
          />
        </el-form-item>


        <el-form-item label="出生日期：" prop="birthday">
          <el-date-picker
              v-model="userParams.birthday"
              style="width: 100%;"
              type="datetime"
              placeholder="请选择出生日期"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>

        <el-form-item label="入学时间：" prop="enterTime">
          <el-date-picker
              v-model="userParams.enterTime"
              style="width: 100%;"
              type="datetime"
              placeholder="请选择入学时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>


        <el-form-item label="用户地址：" prop="address" style="width: 100%">
          <el-input
              v-model="userParams.address"
              maxlength="255"
              show-word-limit
              placeholder="请选择用户地址"
              type="textarea"
          />
        </el-form-item>

      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button type="primary" @click="save(ruleFormRef)">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {CreditCard, Iphone, Minus, Plus, Postcard, User} from "@element-plus/icons-vue";
import {nextTick, onMounted, reactive, ref} from "vue";
import {
  addUserBaseInfo,
  deleteById,
  deleteByIds,
  Page,
  Records, searchByCondition, updateUserBaseInfo
} from "@/api/user/user.ts";
import {ApiResponse} from "@/utils/request.ts";
import {FormInstance, FormRules} from "element-plus";

interface SearchData {
  name: string
  studentNumber: string
  phone: string
  idCard: string
}

// 搜索条件
const searchDataForm = reactive<SearchData>({
  name: '',
  studentNumber: '',
  phone: '',
  idCard: ''
})

const resetForm = () => {
  searchDataForm.name = ''
  searchDataForm.studentNumber = ''
  searchDataForm.phone = ''
  searchDataForm.idCard = ''
}

// 默认页码
const pageNum = ref<number>(1);
// 默认每页条数
const pageSize = ref<number>(10);
// 总条数
const totalRow = ref<number>(0);
// 存储表格数据
const records = ref<Records[]>([]);
// 定义响应式数据控制抽屉的显示与隐藏
const drawer = ref<boolean>(false);
// 校验表单的ref
const ruleFormRef = ref<FormInstance>()
//准备一个数组存储批量删除的用户的ID
let selectIdArr = ref<Records[]>([]);
//收集用户信息的响应式数据
let userParams = reactive({
  id: '',
  username: '',
  password: '',
  name: '',
  sex: '1',
  sexText: '',
  studentNumber: '',
  age: 0,
  college: '',
  major: '',
  grade: '',
  idCard: '',
  enterTime: null,
  email: '',
  phone: '',
  birthday: '',
  address: '',
  token: ''
});

//表单校验的规则对象
const rules = reactive<FormRules>({
  //用户名字
  username: [{required: true, trigger: 'blur', message: "请输入用户账号"}],
  //用户的密码
  password: [{required: true, trigger: 'blur', message: "请输入密码"}],
  name: [
    {
      required: true,
      message: '请输入用户姓名',
      trigger: 'blur'
    }
  ],
  sex: [
    {
      required: true,
      message: '请选择用户性别',
      trigger: 'change',
    },
  ],
  studentNumber: [
    {
      required: true,
      message: '请输入用户学号',
      trigger: 'blur'
    }
  ],
  age: [
    {
      required: true,
      message: '请输入用户年龄',
      trigger: 'blur'
    }
  ],
  phone: [
    {
      required: true,
      message: '请输入用户电话',
      trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入用户邮箱',
      trigger: 'blur'
    }
  ],
  idCard: [
    {
      required: true,
      message: '请输入正确的身份证号',
      trigger: 'blur'
    }
  ],
  birthday: [
    {
      required: true,
      message: '请选择出生日期',
      trigger: 'change'
    }
  ],
  address: [
    {
      required: true,
      message: '请输入用户地址',
      trigger: 'blur'
    }
  ]
})


onMounted(() => {
  getHasUser()
})

const getHasUser = async () => {
  const data = {
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }
  const result: ApiResponse<Page<Records>> = await searchByCondition(data);
  if (result.code === 1000_0000) {
    totalRow.value = result.data.totalRow
    records.value = result.data.records
  }
}

// 搜索
const searchForm = async () => {
  const data = {
    name: searchDataForm.name,
    studentNumber: searchDataForm.studentNumber,
    phone: searchDataForm.phone,
    idCard: searchDataForm.idCard,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  }
  const result: ApiResponse<any> = await searchByCondition(data)
  if (result.code === 1000_0000) {
    totalRow.value = result.data.totalRow
    records.value = result.data.records
  }
}

// 添加用户
const addUser = () => {
  drawer.value = true
  //清空数据
  Object.assign(userParams, {
    id: '',
    username: '',
    password: '',
    name: '',
    sex: '1',
    sexText: '',
    studentNumber: '',
    age: 0,
    college: '',
    major: '',
    grade: '',
    idCard: '',
    enterTime: null,
    email: '',
    phone: '',
    birthday: '',
    address: '',
    token: ''
  });
  //清除上一次的错误的提示信息
  nextTick(() => {
    ruleFormRef.value?.clearValidate('username');
    ruleFormRef.value?.clearValidate('password');
  });
}

// 更新用户
const updateUser = (row: any) => {
  drawer.value = true
  //存储收集已有的账号信息
  Object.assign(userParams, row);
  //清除上一次的错误的提示信息
  nextTick(() => {
    ruleFormRef.value?.clearValidate('username');
    ruleFormRef.value?.clearValidate('password');
  });
}

//保存按钮的回调
const save = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid, fields) => {
    if (!valid) {
      return
    }
    // 保存按钮:添加新的用户|更新已有的用户账号信息
    const result = userParams.id ? await updateUserBaseInfo(userParams) : await addUserBaseInfo(userParams)
    //添加或者更新成功
    if (result.code == 1000_0000) {
      //关闭抽屉
      drawer.value = false;
      //提示消息
      ElMessage({type: 'success', message: userParams.id ? '更新成功' : '添加成功'});
      //浏览器自动刷新一次
      await getHasUser()
    }
  })
}

// 日期格式化
const formatDate = (date: Date) => {
  let year = date.getFullYear();
  let month = (date.getMonth() + 1).toString().padStart(2, '0');
  let day = date.getDate().toString().padStart(2, '0');
  let hours = date.getHours().toString().padStart(2, '0');
  let minutes = date.getMinutes().toString().padStart(2, '0');
  let seconds = date.getSeconds().toString().padStart(2, '0');
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// 取消按钮的回调
const cancel = () => {
  //关闭抽屉
  drawer.value = false;
}


// 删除某一个用户
const deleteUser = async (userId: string) => {
  let result: any = await deleteById(userId);
  if (result.code === 1000_0000) {
    ElMessage({type: 'success', message: '删除成功'});
    await getHasUser();
  }
}

//table复选框勾选的时候会触发的事件
const selectChange = (value: any) => {
  selectIdArr.value = value;
}

//批量删除按钮的回调
const deleteSelectUser = async () => {
  //整理批量删除的参数
  let idsList: any = selectIdArr.value.map(item => item.id);
  //批量删除的请求
  let result: any = await deleteByIds(idsList);
  if (result.code === 1000_0000) {
    ElMessage({type: 'success', message: '删除成功'});
    getHasUser();
  }
}

</script>

<style scoped lang="scss">
.top {
  margin-bottom: 2vh;

  .search-form {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .el-form-item {
      margin-bottom: 0;

      .el-input {
        width: 220px;
      }
    }
  }
}

.bottom {

  .bottom-table {
    margin: 2vh 0;

    .unfold-card {
      background-color: rgba(135 206 250 / .5);

      .unfold {
        width: 40%;
        display: flex;
        justify-content: space-between;

        p:first-child {
          margin-top: 0;
        }
      }
    }
  }
}

.dialog-add-or-update-form {
  width: 100%;
  display: flex;
  justify-content: space-between;

  .el-form-item {
    width: 45%;
  }
}

</style>

